﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FastFoodToNight.Models;
using FastFoodToNight.ViewModels;
namespace FastFoodToNight.Models
{
    public class ShoppingCart
    {
        public List<CartItem> items { get; private set; }
        public static readonly ShoppingCart Instance;
        static ShoppingCart()
        {
            if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
            {
                Instance = new ShoppingCart();
                Instance.items = new List<CartItem>();
                HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
            }
            else
            {
                Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
            }
        }
        protected ShoppingCart() { }

        public void AddItem(int id)
        {

            CartItem newItem = new CartItem(id);
            if (items.Contains(newItem))
            {
                foreach (CartItem item in items)
                {
                    if (item.Equals(newItem))
                    {
                        item.soluong++;
                        return;
                    }
                }
            }
            else
            {
                newItem.soluong = 1;
                items.Add(newItem);
            }
        }

        public void SetItemQuantity(int id, int masanpham)
        {
            // If we are setting the quantity to 0, remove the item entirely
            if (masanpham == 0)
            {
                RemoveItem(id);
                return;
            }
            // Find the item and update the quantity
            CartItem updatedItem = new CartItem(id);
            foreach (CartItem item in items)
            {
                if (item.Equals(updatedItem))
                {
                    item.masanpham = masanpham;
                    return;
                }
            }
        }

        public void RemoveItem(int id)
        {
            CartItem removedItem = new CartItem(id);
            items.Remove(removedItem);
        }
    }
}